<?php

/**
 * 作者：云喵软件开发工作室
 * 官网：https://www.meoyun.com
 */

namespace app\api\controller;

use support\Request;
use support\Response;
use app\model\UsersModel;
use app\model\UserFollowModel;
use app\model\MessageModel;
use app\service\MessageService;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;

/**
 * 用户控制器
 */
class User extends BaseApi
{

    //获取用户信息
    public function getInfo(Request $request): Response
    {
        $userId = $this->getUserId();

        // 查询用户信息
        $user = UsersModel::find($userId);

        if (!$user) {
            return $this->fail('用户不存在',2001);
        }

        return $this->success($user);
    }

    //更新用户信息
    public function updateProfile(Request $request): Response
    {
        try {
            $params = v::input($request->post(), [
                'field' => v::notEmpty()->setName('字段名'),
                'value' => v::notEmpty()->setName('字段值')
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $userId = $this->getUserId();
        $field = $params['field'];
        $value = $params['value'];

        // 定义允许更新的字段
        $allowedFields = ['sn','nickname', 'avatar', 'phone', 'email', 'gender', 'birthday', 'introduction'];

        if (!in_array($field, $allowedFields)) {
            return $this->fail('不允许更新该字段');
        }

        // 查询用户信息
        $user = UsersModel::find($userId);
        if (!$user) {
            return $this->fail('用户不存在');
        }

        // 更新用户信息
        $user->$field = $value;
        $user->save();

        return $this->success($user, '更新成功');
    }

//    保存用户信息
    public function saveInfo(Request $request): Response
    {
        try {
            $params = v::input($request->post(), [
                'nickname' => v::optional(v::stringType()->length(2, 24))->setName('昵称'),
                'avatar' => v::optional(v::stringType()->length(1, 255))->setName('头像'),
                'phone' => v::optional(v::stringType()->length(1, 20))->setName('手机号'),
                'email' => v::optional(v::email()->length(1, 20))->setName('邮箱'),
                'gender' => v::optional(v::intType()->between(0, 2))->setName('性别'),
                'birthday' => v::optional(v::date('Y-m-d'))->setName('生日'),
                'introduction' => v::optional(v::stringType()->length(1, 100))->setName('个人简介')
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $userId = $this->getUserId();

        // 查询用户信息
        $user = UsersModel::find($userId);
        if (!$user) {
            return $this->fail('用户不存在', 2001);
        }

        // 检查手机号是否已被其他用户使用
        if (isset($params['phone']) && $params['phone']) {
            $existingUser = UsersModel::where('phone', $params['phone'])
                ->where('id', '!=', $userId)
                ->first();
            if ($existingUser) {
                return $this->fail('手机号已被其他用户使用');
            }
        }

        // 检查邮箱是否已被其他用户使用
        if (isset($params['email']) && $params['email']) {
            $existingUser = UsersModel::where('email', $params['email'])
                ->where('id', '!=', $userId)
                ->first();
            if ($existingUser) {
                return $this->fail('邮箱已被其他用户使用');
            }
        }

        // 更新用户信息
        foreach ($params as $field => $value) {
            if ($value !== null) {
                $user->$field = $value;
            }
        }

        // 保存更新
        if ($user->save()) {
            return $this->success($user, '用户信息更新成功');
        } else {
            return $this->fail('用户信息更新失败');
        }
    }

    // 关注用户
    public function follow(Request $request): Response
    {
        try {
            $params = v::input($request->post(), [
                'follow_user_id' => v::notEmpty()->setName('被关注用户ID')
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $userId = $this->getUserId();
        $followUserId = $params['follow_user_id'];

        // 检查被关注用户是否存在
        $followUser = UsersModel::find($followUserId);
        if (!$followUser) {
            return $this->fail('用户不存在');
        }

        // 不能关注自己
        if ($userId === $followUserId) {
            return $this->fail('不能关注自己');
        }

        // 检查是否已经关注
        if (UserFollowModel::isFollowing($userId, $followUserId)) {
            return $this->fail('已经关注该用户');
        }

        // 执行关注操作
        $result = UserFollowModel::followUser($userId, $followUserId);
        if ($result) {
            // 发送关注通知消息给被关注用户
            MessageService::sendMessage(
                $userId,
                $followUserId,
                '关注了你',
                MessageModel::TYPE_FOLLOW
            );
            
            return $this->success(null, '关注成功');
        } else {
            return $this->fail('关注失败');
        }
    }

    // 取消关注用户
    public function unfollow(Request $request): Response
    {
        try {
            $params = v::input($request->post(), [
                'follow_user_id' => v::notEmpty()->setName('被关注用户ID')
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $userId = $this->getUserId();
        $followUserId = $params['follow_user_id'];

        // 检查是否已关注
        if (!UserFollowModel::isFollowing($userId, $followUserId)) {
            return $this->fail('未关注该用户');
        }

        // 执行取消关注操作
        $result = UserFollowModel::unfollowUser($userId, $followUserId);
        if ($result) {
            return $this->success(null, '取消关注成功');
        } else {
            return $this->fail('取消关注失败');
        }
    }

    // 检查关注状态
    public function checkFollowStatus(Request $request): Response
    {
        try {
            $params = v::input($request->get(), [
                'follow_user_id' => v::notEmpty()->setName('被关注用户ID')
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $userId = $this->getUserId(false);
        $followUserId = $params['follow_user_id'];

        $isFollowing = UserFollowModel::isFollowing($userId, $followUserId);
        $isMutualFollowing = UserFollowModel::isMutualFollowing($userId, $followUserId);

        return $this->success([
            'is_following' => $isFollowing,
            'is_mutual_following' => $isMutualFollowing,
            'follow_user_id' => $followUserId
        ]);
    }

    // 通过用户ID获取用户信息
    public function getUserById(Request $request): Response
    {
        try {
            $params = v::input($request->get(), [
                'user_id' => v::notEmpty()->setName('用户ID')
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $userId = $params['user_id'];

        // 查询用户信息
        $user = UsersModel::find($userId);

        if (!$user) {
            return $this->fail('用户不存在');
        }

        // 获取用户统计信息
        $followCount = UserFollowModel::where('user_id', $userId)->count();
        $fansCount = UserFollowModel::where('follow_user_id', $userId)->count();

        // 添加统计信息到用户数据
        $userData = $user->toArray();
        $userData['follow_count'] = $followCount;
        $userData['fans_count'] = $fansCount;

        return $this->success($userData);
    }

    /**
     * 获取热门用户列表
     * @param Request $request
     * @return Response
     */
    public function getHotUsers(Request $request): Response
    {

        try {
            // 获取热门用户，按粉丝数排序
            $users = UsersModel::select(['id', 'sn', 'nickname', 'avatar', 'introduction', 'created_at'])
                ->where('status', 1)
                ->orderBy('post_thumb_count', 'desc')
                ->orderBy('post_count', 'desc')
                ->orderBy('created_at', 'desc')
                ->limit(10)
                ->get();
            return $this->success($users);
            
        } catch (\Exception $e) {
            return $this->fail('获取热门用户失败：' . $e->getMessage());
        }
    }
}
